package cn.com.greatwall.flowable.rest;

import java.util.Set;

import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.com.greatwall.common.exception.BadRequestException;
import cn.com.greatwall.flowable.domain.Form;
import cn.com.greatwall.flowable.service.FormService;
import cn.com.greatwall.flowable.service.dto.criteria.FormQueryCriteria;
import cn.com.greatwall.logging.annotation.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author herw
 * @Time 2020-08-31 15:38:55
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
@Slf4j
@Api(tags = "表单设计：表单管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/form")
public class FormController {
    private final FormService formService;
    private static final String ENTITY_NAME = "form";

    @Log("查询表单")
    @ApiOperation("查询表单")
    @GetMapping
    @PreAuthorize("@el.check('job:list','user:list')")
    public ResponseEntity<Object> query(FormQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(formService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    
    @Log("新增表单")
    @ApiOperation("新增表单")
    @PostMapping
    @PreAuthorize("@el.check('job:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Form resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        formService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
    
    @Log("修改表单")
    @ApiOperation("修改表单")
    @PutMapping
    @PreAuthorize("@el.check('job:edit')")
    public ResponseEntity<Object> update(@Validated(Form.Update.class) @RequestBody Form resources){
        formService.update(resources);
        return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
    }
    
    @Log("删除表单")
    @ApiOperation("删除表单")
    @DeleteMapping
    @PreAuthorize("@el.check('job:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
        formService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
